package com.youth.platform.validator;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.youth.platform.entity.RegisterInfo;

public class RegisterValidator implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		return RegisterInfo.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object obj, Errors errors) {
		RegisterInfo info = (RegisterInfo) obj;
		
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession session = attr.getRequest().getSession();
		Object attribute = session.getAttribute("verifyCode");
		session.removeAttribute("verifyCode");
		if (null == attribute || StringUtils.isBlank(attribute.toString()) || StringUtils.isBlank(info.getVerifyCode()) 
				|| !info.getVerifyCode().equalsIgnoreCase(attribute.toString()))
		{
			errors.reject("verifycode.error", "验证码错误");
		}
		
		
		ValidationUtils.rejectIfEmpty(errors, "confirmPassword", "empty.password",
				"密码不能为空");
	}

}
